<template>
	<view >
		<view class="detail-container" v-if="!showEmpty">
			<view class="step">
				<u-steps :current="current" activeColor="#920076">
					<u-steps-item title="待审核"></u-steps-item>
					<u-steps-item :error="form.status === '2'"
						:title="form.status === '0' ? '审核' : (form.status === '2' ? '审核拒绝': '审核通过')"></u-steps-item>
					<u-steps-item :error="form.status === '4'"
						:title="parseInt(form.status)< 3 ? '核验' : (form.status === '3' ? '核验通过': '核验拒绝')"></u-steps-item>
				</u-steps>
			</view>

			<view class="add-container">
				<u-form v-show="form.type === '1'" :model="form" :labelStyle="lstyle" labelPosition="left" label-width="110" label-align="left"
					:rules="rules" ref="uForm1" class="form-container">
					<view class="header">
						<view class="logo">访</view>
						<view class="title">被访人信息</view>
					</view>
					<u-form-item v-show="showVisited" label="被访人姓名"  prop="visitedNameLabel" required borderBottom>
						<u-input readonly fontSize="14px"   v-model="form.visitedNameLabel" border="none"
							placeholder=""></u-input>
					</u-form-item>
					<u-form-item label="被访人电话" prop="visitedPhone" required borderBottom>
						<u-input fontSize="14px"  :readonly="isReadonly" type="number" v-model="form.visitedPhone" border="none"
							maxlength="11" placeholder="请输入被访人电话"></u-input>
					</u-form-item>
					

				</u-form>

				<u-form :model="form" :labelStyle="lstyle" labelPosition="left" label-width="110" label-align="left"
					:rules="rules" ref="uForm2" class="form-container mg-top30">
					<view class="header">
						<view class="logo">客</view>
						<view class="title">访客信息</view>
					</view>

					<u-form-item label="访客姓名" prop="appointName" required borderBottom>
						<u-input fontSize="14px"  :readonly="isReadonly" v-model="form.appointName" border="none"
							placeholder="请输入访客姓名"></u-input>
					</u-form-item>
					<u-form-item label="访客电话" prop="appointPhone" required borderBottom>
						<u-input fontSize="14px"  :readonly="isReadonly" type="number" v-model="form.appointPhone" border="none"
							maxlength="11" placeholder="请输入访客电话"></u-input>
					</u-form-item>
					<u-form-item label="访客单位" prop="appointDept" required borderBottom>
						<u-input fontSize="14px" :readonly="isReadonly"  v-model="form.appointDept" border="none" maxlength="11"
							:placeholder="isReadonly? '' : '请输入访客单位'"></u-input>
					</u-form-item>
					<u-form-item label="来访人数" prop="num" required borderBottom>
							<u-input fontSize="14px" :readonly="isReadonly" type="number" v-model="form.num" border="none" maxlength="5"
								:placeholder="isReadonly? '' : '请输入来访人数'"></u-input>
						</u-form-item>
					</u-form-item>
					<!-- <u-form-item label="访客身份证" prop="cardNo"  borderBottom>
						<u-input fontSize="14px"  :readonly="isReadonly" type="idcard" v-model="form.cardNo" border="none" maxlength="18"
							:placeholder="isReadonly? '' : '请输入访客身份证'"></u-input>
					</u-form-item> -->

					<u-form-item  label="到访日期" prop="appointTime" required borderBottom
						@click="showPicker">
						<u-input fontSize="14px"  style="pointer-events: none;  user-select: none;min-width: 300rpx;" v-model="form.appointTime" border="none"
							maxlength="20" placeholder="请输入到访日期"></u-input>
						<u-datetime-picker ref="datetimePicker" :minDate="minDate" :show="showDatePicker" :formatter="formatter"
							v-model="nowDate" @confirm="handlePickDate" @cancel="showDatePicker = false"
							mode="datetime"></u-datetime-picker>
					</u-form-item>

					<u-form-item label="来访事由" prop="appointRemark" required borderBottom @click="showPickerRemark">
						<u-input fontSize="14px"  style=" pointer-events: none; user-select: none;min-width: 300rpx;" v-model="form.appointRemark"
						border="none" maxlength="20" placeholder="请输入来访事由"></u-input>
					
						<u-picker :show="showRemarkPicker" @confirm="handlePickRemark" @cancel="showRemarkPicker = false"
							:columns="remarks"></u-picker>
					</u-form-item>
				</u-form>

				<u-form :model="form" :labelStyle="lstyle" labelPosition="left" label-width="110" label-align="left"
					:rules="rules" ref="uForm3" class="form-container mg-top30 mb60">
					<view class="header">
						<view class="logo">同</view>
						<view class="title">同行人</view>
					</view>

					<u-cell-group>
						<u-cell v-for="(person,index) in form.list" @click="editCompanions(index)" :title="person.name"
							:isLink="true"></u-cell>
						<u-cell v-if="form.status === '0'" @click="addCompanions" :isLink="true" value="新增"></u-cell>
					</u-cell-group>
				</u-form>

				<view class="submit" v-if="form.status === '0'">
					<u-button color="#920076" :loading="loading" @click="submit">修改</u-button>
				</view>

				<u-notify ref="uNotify" message="预约成功"></u-notify>
			</view>


		</view>
		<view class="empty" v-else="showEmpty">
			<u-empty icon="/static/empty.png" iconColor="#ccc" mode="data" text="暂无数据">
			</u-empty>
		</view>
	</view>
</template>

<script>
	import moment from 'moment';
	import {
		getOpenid,
		desensitizeName
	} from "@/common/permission.js"
import { isReadonly } from 'vue';
	export default {
		data() {
			return {
				loading: false,
				showVisited: true,
				showRemarkPicker: false,
				remarks:[['业务交流','公司参观','技术交流','参加会议','供应商施工','面试','其他']],
				show: false,
				showEmpty: false,
				current: null,
				//真实的被访人姓名
				realVisitedName: '',
				show: false,
				id: '',
				minDate: Number(new Date()),
				nowDate: Number(new Date()),
				showDatePicker: false,
				form: {
					status: '',
					visitedNameLabel: '',
					visitedName: '',
					visitedPhone: '',
					appointName: '',
					appointPhone: '',
					cardNo: '',
					appointDept: '',
					appointTime: '',
					type: '', //预约类型 1-我的预约 2-代客预约
					list: [], //同行人信息
				},
				rules: {
					visitedName: [{
						required: true,
						message: '请输入被访人姓名',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							if (this.realVisitedName &&
								this.realVisitedName != this.form.visitedName) {
								return false
							} else {
								return true
							}
						},
						message: '请输入正确的被访人姓名',
						// 触发器可以同时用blur和change
						trigger: ['blur'],
					}],
					visitedPhone: [{
							required: true,
							message: '请输入被访人电话',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								return uni.$u.test.mobile(value);
							},
							message: '请输入正确的手机号',
							// 触发器可以同时用blur和change
							trigger: ['blur'],
						}, {
							asyncValidator: (rule, value, callback) => {
								this.$request({
									url: '/appoint/getUserInfo?phone=' + value
								}).then(res => {
									if (res.data) {
										this.form.visitedNameLabel = desensitizeName(res.data.name)
										this.form.visitedName = res.data.name
										this.showVisited = true
										console.log("8888",this.form.visitedNameLabel)
										callback()
									} else {
										this.form.visitedName = ''
										this.form.visitedNameLabel = ''
										this.showVisited = false
										console.log("99999",this.form)
										callback(new Error('被访人不存在或没权限访问'));
									}
								}).catch(() => {
									this.form.visitedNameLabel = ''
									this.form.visitedName = ''
									this.showVisited = false
									callback(new Error('被访人不存在或没权限访问'));
								})

							},
							trigger: ['blur'],
							// 如果是异步校验，无需写message属性，错误的信息通过Error抛出即可
							// message: 'xxx'
						}
					],
					appointName: [{
						required: true,
						message: '请输入访客姓名',
						trigger: ['blur', 'change']
					}],
					appointPhone: [{
							required: true,
							message: '请输入访客电话',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								return uni.$u.test.mobile(value);
							},
							message: '请输入正确的手机号',
							// 触发器可以同时用blur和change
							trigger: ['blur', 'change'],
						}
					],
					appointDept: [{
						required: true,
						message: '请输入访客单位',
						trigger: ['blur', 'change']
					}],
					num: [{
						required: true,
						message: '请输入来访人数',
						trigger: ['blur', 'change']
					}],
					cardNo: [{
						required: false,
						message: '请输入访客身份证',
						trigger: ['blur', 'change']
					}, 
					// {
					// 	validator: (rule, value, callback) => {
					// 		// 上面有说，返回true表示校验通过，返回false表示不通过
					// 		// uni.$u.test.mobile()就是返回true或者false的
					// 		const regex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
					// 		return regex.test(value);
					// 	},
					// 	message: '请输入正确的身份证',
					// 	// 触发器可以同时用blur和change
					// 	trigger: ['blur'],
					// },
					],
					appointRemark: [{
						required: true,
						message: '请输入来访事由',
						trigger: ['blur', 'change']
					}],
					appointTime: [{
						required: true,
						message: '请输入到访日期',
						trigger: ['blur', 'change']
					}],
				}
			}
		},
		onShow() {
			const companions = uni.getStorageSync("companions") || []
			if (companions) {
				this.form.list = companions
				uni.removeStorageSync("companions")
			}
		},
		onReady() {
			// this.$refs.datetimePicker.setFormatter(this.formatter)
		},
		computed: {
			lstyle() {
				return {
					fontSize: '32rpx'
				}
			},
			// current(){
			// 	if(this.form.status === '0'){
			// 		return 0
			// 	}else if(this.form.status === '1' || this.form.status === '2'){
			// 		return 1
			// 	}else if(this.form.status === '3' || this.form.status === '4'){
			// 		return 2
			// 	}
			// },
			isReadonly() {
				return this.form.status !== '0'
			}
		},
		async onLoad(e) {
			console.log("onload =====", e)
			if (e.id) {
				this.id = e.id
				this.loadData()
			} else {
				this.showEmpty = true
			}
		},
		methods: {
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				if (type === 'hour') {
					return `${value}时`
				}
				if (type === 'minute') {
					return `${value}分`
				}
				return value
			},
			loadData() {
				uni.showLoading()
				this.$request({
					url: '/appoint/detail?id=' + this.id
				}).then(res => {
					res.data.visitedNameLabel = desensitizeName(res.data.visitedName)
					this.form = res.data
					if (this.form.status === '0') {
						this.current = 0
					} else if (this.form.status === '1' || this.form.status === '2') {
						this.current = 1
					} else if (this.form.status === '3' || this.form.status === '4') {
						this.current = 2
					}
					this.showEmpty = false
					this.show = true
				}).catch(this.showEmpty = true)
				.finally(() => {
					console.log("当前current============>", this.current)
					uni.hideLoading()
					this.show = true
				})
			},
			addCompanions() {
				if (this.form.list && this.form.list.length > 0) {
					uni.setStorageSync("companions", this.form.list)
				}
				uni.navigateTo({
					url: "/pages/reservation/companions"
				})
			},
			editCompanions(index) {
				if (this.form.list && this.form.list.length > 0) {
					uni.setStorageSync("companions", this.form.list)
				}
				uni.navigateTo({
					url: "/pages/reservation/companions?index=" + index +"&status=" + this.form.status
				})
			},
			handlePickDate(e) {
				this.showDatePicker = false
				this.form.appointTime = moment(e.value).format('YYYY-MM-DD HH:mm')
			},
			showPicker() {
				if (this.form.status === '0') {
					this.showDatePicker = true
				}
			},
			showPickerRemark(){
				if (this.form.status === '0') {
					this.showRemarkPicker = true
				}
			},
			handlePickRemark(e) {
				this.showRemarkPicker = false
				this.form.appointRemark = e.value[0]
			},
			submit() {
				this.$refs.uForm1.validate().then(res => {
					this.$refs.uForm2.validate().then(res => {
						console.log("校验通过")
						this.loading = true
						uni.showLoading({
							title: '提交中...'
						})
						this.$request({
							method: 'POST',
							header: {
								"Content-Type": "application/json"
							},
							data: {
								...this.form,
							},
							url: '/appoint/edit'
						}).then(res => {
							this.$refs.uNotify.show({
								top: 10,
								type: 'success',
								message: '修改成功',
								duration: 1000 * 1,
								safeAreaInsetTop: true
							})
							setTimeout(() => {
								uni.redirectTo({
									url: "/pages/reservation/reservation"
								})
							}, 1100)
						}).catch(e => {
							uni.showModal({
								title: '温馨提示',
								content: e.msg,
								showCancel: false
							})
						}).finally(()=>{
							uni.hideLoading()
							this.loading = false
						})
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.input-placeholder{
		font-size: 12px;
	}
	.empty {
		display: flex;
		justify-content: center;
		background: #f3f3f3;
		width: 100%;
		height: 100vh;
	}
	.detail-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		min-height: 100vh;
		background: #f3f3f3;

		.step {
			margin-top: 30rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			background: #fff;
			border-radius: 10rpx;
			width: 94%;
			height: 132rpx;

		}

		.add-container {
			width: 100%;
			min-height: 100vh;
			background: #f3f3f3;
			display: flex;
			flex-direction: column;
			align-items: center;
			padding-top: 30rpx;
			// justify-content: center;

			.mg-top30 {
				margin-top: 16rpx;
			}

			.mb60 {
				margin-bottom: 60rpx;
			}

			.header {
				display: flex;
				align-items: center;
				font-size: 26rpx;
				color: #888888;
				margin-bottom: 16rpx;
				// height: 70rpx;

				.logo {
					margin-left: -48rpx;
					height: 40rpx;
					width: 40rpx;
					line-height: 40rpx;
					font-size: 28rpx;
					border: 1px solid #3cbfad;
					color: #3cbfad;
					text-align: center;
					border-radius: 50%
				}

				.title {
					// height: 40rpx;
					// line-height: 40rpx;
					margin-left: 10rpx;
					// margin-bottom: 20rpx;
				}

			}

			.submit {
				width: 94%;
				margin-bottom: 60rpx;
			}

			.form-container {
				background: #fff;
				border-radius: 10rpx;
				padding: 20rpx 40rpx 30rpx 60rpx;
				width: 80%;
			}



		}
	}
</style>